<template>
  <el-dialog
    v-model="visible"
    :title="fileTitle"
    width="39%"
    :before-close="handleClose"
    class="dark-dialog report-preview-dialog"
    :show-close="false"
    align-center
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="costom-header">
        <div :id="titleId" :class="titleClass">{{ fileTitle }}</div>
        <div class="actions">
          <el-tooltip
            effect="dark"
            content="导出报告"
            placement="bottom"
          >
            <el-button
              v-if="!isExporting"
              size="large"
              link
              :icon="Download"
              @click="exportReport"
            ></el-button>
            <el-button
              v-if="isExporting"
              size="large"
              link
              :icon="Loading"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="关闭" placement="bottom">
            <el-button
              size="large"
              link
              @click="close"
              :icon="Close"
            ></el-button>
          </el-tooltip>
        </div>
      </div>
    </template>
    
    <div class="pdf-progress" v-if="isExporting">
      <el-progress 
        :percentage="exportProgress" 
        status="success"
        :text-inside="true" 
        :stroke-width="5" 
        striped-flow
        striped 
      />
    </div>
    
    <div class="pdf-div">
      <div class="pdf-preview" id="reportPreview" ref="reportPreviewRef">
        <div style="height: 80px;"></div>
        
        <div class="pdf-title">
          方量报告
        </div>
        
        <div class="pdf-subtitle">
          池州创亿矿业
        </div>
        
        <div style="height: 500px;"></div>
        
        <div class="pdf-company">
          青阳综管平台
        </div>
        
        <div class="pdf-date">
          2025年5月29日
        </div>
        
        <div style="height: 230px;"></div>
        
        <div class="pdf-radar">
          <div class="pdf-radar-title">报告背景</div>
          <div class="pdf-radar-content">&emsp;&emsp;本报告旨在通过对比两期地质模型数据，分析某区域内不同地层的挖方差异，为 [矿山开采 / 政府监管等] 提供土方量计算依据。</div>
          
          <div class="pdf-radar-title">区域范围</div>
          <div class="region-image">
            <img src="./qxsy.png" alt="区域图片" style="width: 100%; max-width: 400px; height: auto;" />
          </div>
          <div class="pdf-chart-title">[[92.943334, 42.386639], [92.397684, 42.377998], [92.340608, 42.377998], [92.842253, 42.377707]]</div>
          
          <div class="pdf-radar-title">数据来源</div>
          <div class="pdf-uav-table">
            <el-table :data="dataSourceTable" border style="width: 100%">
              <el-table-column prop="date" label="数据获取日期" align="center" />
              <el-table-column prop="source" label="数据来源" align="center" />
              <el-table-column prop="accuracy" label="数据精度" align="center" />
            </el-table>
          </div>
          
          <div class="model-images">
            <div class="model-image-item">
              <img src="./qxsy.png" alt="实景模型" style="width: 100%; height: auto;" />
              <div class="image-title">实景模型</div>
            </div>
            
           
          </div>

          <div class="model-images">
             <div class="model-image-item">
              <img src="./dzmx.png" alt="地形模型" style="width: 100%; height: auto;" />
              <div class="image-title">地形模型</div>
            </div>
          </div>

           <div class="model-images">
             <div class="model-image-item">
              <img src="./qxsy.png" alt="倾斜模型" style="width: 100%; height: auto;" />
              <div class="image-title">倾斜模型</div>
            </div>
          </div>
          
          <div style="height: 50px;"></div>
          
          <div class="pdf-radar-title">分析方法</div>
          <div class="pdf-radar-content">&emsp;&emsp;基于【栅格数据对比】/ 实体模型布尔运算方法，提取两期模型中指定区域、不同地层的体积差异。</div>
          
          <div class="pdf-radar-title">分析结果</div>
          
          <div class="pdf-chart">
            <div ref="chartRef" class="chart-area"></div>
          </div>
          <div class="pdf-chart-title">区域内剩余方量分析</div>
          
          <div class="pdf-uav-table">
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column prop="name" label="岩层名称" align="center" />
              <el-table-column prop="excavated" label="已开采（方）" align="center" />
              <el-table-column prop="excavatedRate" label="占比" align="center" />
              <el-table-column prop="remaining" label="剩余方量（方）" align="center" />
              <el-table-column prop="remainingRate" label="剩余占比" align="center" />
            </el-table>
          </div>
          
          <div style="height: 30px;"></div>
          
          <div class="pdf-chart">
            <div ref="barChartRef" class="chart-area"></div>
          </div>
          <div class="pdf-chart-title">区域内剩余方量分析</div>
          
          <div class="pdf-uav-table">
            <el-table :data="barTableData" border style="width: 100%">
              <el-table-column prop="name" label="岩层名称" align="center" />
              <el-table-column prop="excavated" label="已开采（方）" align="center" />
              <el-table-column prop="excavatedRate" label="占比" align="center" />
              <el-table-column prop="remaining" label="剩余方量（方）" align="center" />
              <el-table-column prop="remainingRate" label="剩余占比" align="center" />
            </el-table>
          </div>
          
          <div class="pdf-radar-title">报告结论</div>
          <div class="pdf-radar-content">&emsp;&emsp;基于2025年4月1日与2025年5月12日两期数据分析，统计区域内合计挖方35.56万，主要集中在溶剂用白云岩矿 12.6万m³、建筑用灰岩矿11.25万m³。区域内剩余方量合计1433.5万m³，其中溶剂用白云岩矿314.5万m³、电石用石灰岩矿157.6万m³、建筑用灰岩矿546.4万m³。建议继续监测该区域的变化情况，确保施工安全和质量。</div>
          
          <div style="height: 96px;"></div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick, getCurrentInstance } from 'vue'
import { Close, Download, Loading } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

const { proxy } = getCurrentInstance()

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emits('update:modelValue', value)
})
const fileTitle = ref('方量报告')
const isExporting = ref(false)
const exportProgress = ref(0)
const currentDate = ref('')
const reportPreviewRef = ref(null)
const chartRef = ref(null)
const barChartRef = ref(null)
let chartInstance = null
let barChartInstance = null

// 数据源表格数据
const dataSourceTable = ref([
  {
    date: '2023年11月23日',
    source: '无人机航测',
    accuracy: '0.01m'
  },
  {
    date: '2023年12月14日',
    source: '无人机航测',
    accuracy: '0.02m'
  },
  {
    date: '2024年01月29日',
    source: '无人机航测',
    accuracy: '0.02m'
  }
])

// 饼图表格数据
const tableData = ref([
  {
    name: '溶剂用白云岩矿',
    excavated: '12.6万',
    excavatedRate: '35.4%',
    remaining: '314.5万',
    remainingRate: '21.9%'
  },
  {
    name: '电石用石灰岩矿',
    excavated: '8.2万',
    excavatedRate: '23.1%',
    remaining: '157.6万',
    remainingRate: '11.0%'
  },
  {
    name: '建筑用灰岩矿',
    excavated: '11.25万',
    excavatedRate: '31.6%',
    remaining: '546.4万',
    remainingRate: '38.1%'
  },
  {
    name: '其他',
    excavated: '3.51万',
    excavatedRate: '9.9%',
    remaining: '415.0万',
    remainingRate: '29.0%'
  }
])

// 柱状图表格数据
const barTableData = ref([
  {
    name: '溶剂用白云岩矿',
    excavated: '126,000',
    excavatedRate: '33.3%',
    remaining: '31,456,800',
    remainingRate: '66.3%'
  },
  {
    name: '电石用石灰岩矿',
    excavated: '126,000',
    excavatedRate: '33.3%',
    remaining: '31,456,800',
    remainingRate: '18.7%'
  },
  {
    name: '建筑用灰岩矿',
    excavated: '126,000',
    excavatedRate: '33.3%',
    remaining: '31,456,800',
    remainingRate: '8%'
  },
  {
    name: '合计',
    excavated: '378,000',
    excavatedRate: '-',
    remaining: '94,514,470',
    remainingRate: '78.7%'
  }
])

// 计算属性
const totalVolume = computed(() => {
  return '1469.06万'
})

const excavationPercentage = computed(() => {
  return '2.4'
})

const fillPercentage = computed(() => {
  return '97.6'
})

// 初始化当前日期
const initCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  currentDate.value = `${year}年${month}月${day}日`
}

watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    nextTick(() => {
      initChart()
      initBarChart()
    })
  }
})

watch(visible, (newVal) => {
  emits('update:modelValue', newVal)
})

const handleClose = () => {
  visible.value = false
}

const exportReport = () => {
  isExporting.value = true
  exportProgress.value = 0
  downloadPDF(reportPreviewRef.value)
}

const downloadPDF = (page) => {
  exportProgress.value = 20
  html2canvas(page, {
    useCORS: true,
    allowTaint: true,
    scale: 2,
    backgroundColor: '#ffffff'
  }).then((canvas) => {
    exportProgress.value = 48
    canvas2PDF(canvas)
  })
}

const canvas2PDF = (canvas) => {
  exportProgress.value = 50
  const PDF = new jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: 'a4',
  })
  const ctx = canvas.getContext('2d')
  const a4w = 190
  const a4h = 277
  const imgHeight = Math.floor(a4h * canvas.width / a4w)
  let renderedHeight = 0

  while (renderedHeight < canvas.height) {
    let page = document.createElement("canvas")
    page.width = canvas.width
    page.height = Math.min(imgHeight, canvas.height - renderedHeight)

    page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)

    PDF.addImage(page.toDataURL('image/jpeg', 0.2), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width))

    renderedHeight += imgHeight

    if (exportProgress.value < 90) {
      exportProgress.value = exportProgress.value + 5
    }

    if (renderedHeight < canvas.height) {
      PDF.addPage()
    }
  }
  exportProgress.value = 95
  PDF.save("体积计算分析报告.pdf")
  exportProgress.value = 100
  isExporting.value = false
  exportProgress.value = 0
  ElMessage.success('报告导出成功')
}

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  
  const option = {
    title: {
      text: '区域内剩余方量分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['溶剂用白云岩矿', '电石用石灰岩矿', '建筑用灰岩矿']
    },
    series: [
      {
        name: '剩余方量',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 314.5, name: '溶剂用白云岩矿' },
          { value: 157.6, name: '电石用石灰岩矿' },
          { value: 546.4, name: '建筑用灰岩矿' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

const initBarChart = () => {
  if (!barChartRef.value) return
  
  barChartInstance = echarts.init(barChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['剩余方量', '已开采方量']
    },
    xAxis: {
      type: 'category',
      data: ['溶剂用白云岩矿', '电石用石灰岩矿', '建筑用灰岩矿', '建筑用石灰岩矿']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '剩余方量',
        type: 'bar',
        data: [400, 350, 300, 200],
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '已开采方量',
        type: 'bar',
        data: [100, 150, 200, 100],
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  }
  
  barChartInstance.setOption(option)
}

onMounted(() => {
  initCurrentDate()
})
</script>

<style lang="less" scoped>

.pdf-progress {
  position: absolute;
  width: 100%;
  top: 50px;
  left: 0;
  :deep(.el-progress-bar__outer) {
    background-color: transparent;
  }
  :deep(.el-progress-bar__inner) {
    line-height: 20px;
  }
}

.pdf-div {
  height: calc(100vh - 110px);
  overflow-y: auto;
  background: #fff;
  
  .pdf-preview {
    border: 0px;
    text-align: center;
    color: black;
    padding: 0px 100px;
    box-sizing: border-box;
    
    .pdf-title {
      font-family: '黑体';
      font-size: 24px;
    }
    
    .pdf-subtitle {
      margin-top: 10px;
      font-family: '黑体';
      font-size: 16px;
    }
    
    .pdf-company {
      font-family: '黑体';
      font-size: 18px;
    }
    
    .pdf-date {
      margin-top: 10px;
      font-family: '黑体';
      font-size: 18px;
      letter-spacing: 3px;
    }
    
    .pdf-radar {
      text-align: left;
      font-family: '仿宋';
      
      .pdf-radar-title {
        font-size: 16px;
        margin-top: 15px;
      }
      
      .pdf-radar-content {
        font-size: 16px;
        margin-top: 10px;
      }
      
      .pdf-chart {
        box-sizing: border-box;
        width: 100%;
        height: 300px;
        padding: 12px 12px;
        display: flex;
        align-items: stretch;
        justify-content: center;
        
        .chart-area {
          width: 100%;
          height: 100%;
        }
      }
      
      .pdf-chart-title {
        text-align: center;
        font-size: 14px;
        font-family: '仿宋';
        font-weight: 600;
        margin-top: 10px;
        margin-bottom: 10px;
      }
      
      .region-image {
        text-align: center;
        margin: 20px 0;
      }
      
      .model-images {
        display: flex;
        justify-content: space-between;
        gap: 20px;
        margin: 20px 0;
        
        .model-image-item {
          flex: 1;
          text-align: center;
          
          img {
            width: 100%;
            height: auto;
            border: 1px solid #ddd;
          }
          
          .image-title {
            margin-top: 10px;
            font-size: 14px;
            font-weight: 600;
          }
        }
      }
      
      .date-labels {
        display: flex;
        justify-content: space-between;
        margin: 10px 0;
        
        .date-label {
          font-size: 14px;
          text-align: center;
          flex: 1;
        }
      }
      
      .pdf-uav-table {
        margin-top: 25px;
        
        :deep(.el-table) {
          background: transparent;
        }
        
        :deep(.el-table tr) {
          background: transparent;
        }
        
        :deep(.el-table th.el-table__cell) {
          background: transparent;
          color: black;
          text-align: center;
        }
        
        :deep(.el-table .cell) {
          color: black;
          text-align: center;
        }
        
        :deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
          background-color: transparent;
        }
        
        :deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
          padding: 8px;
        }
      }
    }
  }
}

.costom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .el-button.is-link {
    color: #fff;
    font-size: 16px;
    font-weight: 600;
  }

  .actions {
    display: flex;
    gap: 8px;
    align-items: center;
  }
}

.report-preview-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 20px 10px;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
}
</style>